<?php

declare(strict_types=1);
/**
 * This file is part of MoChat.
 * @link     https://mo.chat
 * @document https://mochat.wiki
 * @contact  group@mo.chat
 * @license  https://github.com/mochat-cloud/mochat/blob/master/LICENSE
 */
namespace MoChat\Plugin\AutoTag\Task;

use EasyWeChat\Kernel\Exceptions\InvalidConfigException;
use GuzzleHttp\Exception\GuzzleException;
use Hyperf\Contract\StdoutLoggerInterface;
use Hyperf\Crontab\Annotation\Crontab;
use Hyperf\Di\Annotation\Inject;
use MoChat\App\Corp\Contract\CorpContract;
use MoChat\App\WorkContact\Contract\WorkContactContract;
use MoChat\App\WorkContact\Contract\WorkContactEmployeeContract;
use MoChat\App\WorkEmployee\Contract\WorkEmployeeContract;
use MoChat\Plugin\AutoTag\Contract\AutoTagContract;
use MoChat\Plugin\AutoTag\QueueService\KeyWordTag as KeyWordTagQueue;

/**
 * @Crontab(name="keyWordTag", rule="*\/1 * * * *", callback="execute", singleton=true, memo="企业微信-关键词打标签")
 */
class KeyWordTag
{
    /**
     * @Inject
     * @var AutoTagContract
     */
    protected $autoTagService;

    /**
     * 客户表.
     * @Inject
     * @var WorkContactContract
     */
    protected $workContactService;

    /**
     * @Inject
     * @var WorkContactEmployeeContract
     */
    protected $workContactEmployeeService;

    /**
     * @Inject
     * @var WorkEmployeeContract
     */
    protected $workEmployeeService;

    /**
     * @Inject
     * @var CorpContract
     */
    protected $corpService;

    /**
     * @Inject
     * @var KeyWordTagQueue
     */
    private $keyWordTagQueue;

    /**
     * @Inject
     * @var StdoutLoggerInterface
     */
    private $logger;

    public function execute(): void
    {
        $this->logger->info('关键词打标签开始');

        // TODO  需改为 Listener 模式，而不是查表模式
        $corp = $this->corpService->getCorps(['id']);
        foreach ($corp as $item) {
            // 异步处理
            try {
                // 查询企业全部关键词打标签规则【状态:开启】
                $autoTag = $this->autoTagService->getAutoTagByCorpIdStatus([$item['id']], 1, 1, ['id', 'corp_id', 'employees', 'fuzzy_match_keyword', 'exact_match_keyword', 'tag_rule', 'mark_tag_count']);

                foreach ($autoTag as $v) {
                    // 员工
                    $employee = $this->workEmployeeService->getWorkEmployeeByCorpIdWxUserIds($item['id'], explode(',', $v['employees']), ['id']);
                    if (empty($employee)) {
                        continue;
                    }
                    // 员工客户
                    $contactEmployee = $this->workContactEmployeeService->getWorkContactEmployeesByEmployeeIds(array_column($employee, 'id'), ['contact_id']);
                    if (empty($contactEmployee)) {
                        continue;
                    }
                    $contactIds = array_unique(array_column($contactEmployee, 'contactId'));
                    $contactList = $this->workContactService->getWorkContactsById($contactIds, ['id', 'name', 'wx_external_userid']);
                    if (empty($contactList)) {
                        continue;
                    }
                    $this->keyWordTagQueue->handle([$v], $contactList, (int) $item['id']);
                }
            } catch (InvalidConfigException|GuzzleException $e) {
                $this->logger->error('关键词打标签异步调用失败' . $e->getMessage());
            }
        }
        $this->logger->info('关键词打标签完成');
    }
}
